import matplotlib

matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
import os
import sqlalchemy
from sqlalchemy.engine import URL
from data_analyzer import analyze_salary_trend
from data_storage import DB_CONFIG

BASE_PATH = "./zhaopin_system/output/"
os.makedirs(BASE_PATH, exist_ok=True)


def plot_salary_trend(df, keyword, city, save_path=None):
    """绘制平均薪资趋势折线图"""
    plt.figure(figsize=(12, 6), dpi=100)
    plt.plot(df["publish_time"], df["average_salary"], marker="o", linestyle="-", color="#2c3e50")

    # 动态标题（反映搜索关键词和城市）
    plt.title(f"{city}{keyword}岗位平均薪资趋势", fontproperties="SimHei", fontsize=14)
    plt.xlabel("发布日期", fontproperties="SimHei", fontsize=12)
    plt.ylabel("平均薪资（元/月）", fontproperties="SimHei", fontsize=12)
    plt.xticks(rotation=45, ha="right")
    plt.grid(alpha=0.2, linestyle="--")
    plt.tight_layout()

    if save_path:
        plt.savefig(save_path)
        print(f"[SUCCESS] 图片保存至：{save_path}")

    plt.close()


def plot_company_size_pie(df, keyword, city, save_path=None):
    """绘制公司规模分布饼图"""
    size_counts = df["company_size"].value_counts()
    plt.figure(figsize=(8, 6), dpi=100)

    wedges, texts, autotexts = plt.pie(
        size_counts,
        labels=size_counts.index,
        autopct="%1.1f%%",
        textprops={"fontproperties": "SimHei", "size": 10},
    )

    # 动态标题
    plt.title(f"{city}{keyword}岗位公司规模分布", fontproperties="SimHei", fontsize=14)
    plt.axis("equal")

    if save_path:
        plt.savefig(save_path)
        print(f"[SUCCESS] 图片保存至：{save_path}")

    plt.close()


# 交互式数据可视化
def interactive_visualize():
    """交互式选择关键词和城市进行数据可视化"""
    # 获取用户输入
    keyword = input("请输入搜索关键词（例如java开发）：")
    city = input("请输入城市名称（例如成都）：")

    # 使用 SQLAlchemy 的 URL.create 方法构建连接 URL
    db_url = URL.create(
        drivername="mysql+mysqlconnector",
        username=DB_CONFIG['user'],
        password=DB_CONFIG['passwd'],
        host=DB_CONFIG['host'],
        database=DB_CONFIG['database']
    )

    # 使用 URL 对象创建引擎
    engine = sqlalchemy.create_engine(db_url)

    # 使用引擎连接数据库（添加搜索条件）
    query = f"SELECT * FROM jobs WHERE job_title LIKE '%{keyword}%' AND work_city LIKE '%{city}%'"
    with engine.connect() as conn:
        df = pd.read_sql(query, conn)

    if len(df) == 0:
        print(f"[ERROR] 数据库中未找到包含关键词 '{keyword}' 且城市为 '{city}' 的数据！")
        return

    print(f"[INFO] 找到 {len(df)} 条符合条件的数据")

    # 渲染薪资趋势图
    salary_trend_df = analyze_salary_trend(df)
    plot_salary_trend(
        salary_trend_df,
        keyword=keyword,
        city=city,
        save_path=f"{BASE_PATH}{city}_{keyword}_salary_trend.png"
    )

    # 渲染公司规模饼图
    plot_company_size_pie(
        df,
        keyword=keyword,
        city=city,
        save_path=f"{BASE_PATH}{city}_{keyword}_company_size.png"
    )


if __name__ == "__main__":
    interactive_visualize()